using Bases;
using Configs;
using Mgrs;
using Modules.Game.Roles;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Modules.Game
{
    public class GamePanel : MonoBehaviourSimplify
    {
        public Text scoreText;

        public Text nameText;

        public TextMeshProUGUI hpText;

        public Image hpImg;

        public TextMeshProUGUI mpText;

        public Image mpImg;

        private float _hpW;
        private float _mpW;

        private float _time;

        private void Awake()
        {
            nameText.text = HeroModel.Instance.Data.Name;

            _hpW = hpImg.rectTransform.sizeDelta.x;
            _mpW = mpImg.rectTransform.sizeDelta.x;

            RegisterMsg(EventConfig.GameRestart, OnGameRestart);
            RegisterMsg(EventConfig.HeroHit, OnHeroHit);
            RegisterMsg(EventConfig.HeroReleaseSkill, OnHeroReleaseSkill);
            RegisterMsg(EventConfig.ScoreChange, OnScoreChange);

            UpdateView();
        }

        private void Update()
        {
            UpdateSecond();
        }

        protected override void OnBeforeDestroy()
        {
            GUIManager.UnLoadPanel(nameof(GamePanel));
        }

        /// <summary>
        ///     每秒刷新
        /// </summary>
        private void UpdateSecond()
        {
            _time += Time.deltaTime;
            if (_time < 1.0f)
                return;

            _time = 0.0f;
            UpdateHp();
            UpdateMp();
        }

        /// <summary>
        ///     刷新界面
        /// </summary>
        private void UpdateView()
        {
            UpdateHp();
            UpdateMp();
            UpdateScore();
        }

        private void UpdateHp()
        {
            var attr = HeroModel.Instance.Data.Attr;
            hpText.text = attr.CurHp + " / " + attr.TotalHp;

            var curW = _hpW * attr.CurHp / attr.TotalHp;

            hpImg.rectTransform.sizeDelta =
                new Vector2(curW, hpImg.rectTransform.sizeDelta.y);
        }

        private void UpdateMp()
        {
            var attr = HeroModel.Instance.Data.Attr;
            mpText.text = attr.CurMp + " / " + attr.TotalMp;

            var curW = _mpW * attr.CurMp / attr.TotalMp;

            mpImg.rectTransform.sizeDelta =
                new Vector2(curW, mpImg.rectTransform.sizeDelta.y);
        }

        private void UpdateScore()
        {
            scoreText.text = "Score: " + GameModel.Instance.Score;
        }

        private void OnGameRestart(object obj)
        {
            UpdateView();
        }

        private void OnHeroHit(object obj)
        {
            UpdateHp();
        }

        private void OnHeroReleaseSkill(object obj)
        {
            UpdateMp();
        }

        private void OnScoreChange(object obj)
        {
            UpdateScore();
        }
    }
}